package com.muc.plugin.handler;

import com.muc.plugin.dao.MUCDao;
import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.openfire.muc.*;
import org.jivesoftware.openfire.session.ClientSession;
import org.jivesoftware.util.WebManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;

/**
 * affiliation (owner = 拥有者, admin = 管理员, member = 房间成员, outcast = 被排除者)
 * 暂时没用,因为服务器只是把用户持久化到了这个群组里,但是无法替用户加入这个群组并监听
 * 所以客户端直接调用openfire的包
 */
public class MUCActiveJoinGroupIQHandler extends IQHandler {

    private IQHandlerInfo info;

    private static final String MODULE_NAME = "test join group";

    private static final String NAME_SPACE = "xls:test-join-group";

    private static final Logger log = LoggerFactory.getLogger(MUCActiveJoinGroupIQHandler.class);

    public MUCActiveJoinGroupIQHandler() {
        super(MODULE_NAME);
        info = new IQHandlerInfo("query", NAME_SPACE);
    }

    @Override
    public IQ handleIQ(IQ packet) throws UnauthorizedException {
        IQ reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());

        try {
            ClientSession session = sessionManager.getSession(packet.getFrom());
            if (session == null) {
                log.error("Error during userInfo. Session not found in" +
                        " sessionManager.getPreAuthenticatedKeys()" +
                        " for key" + packet.getFrom());
                reply.setError(PacketError.Condition.internal_server_error);
                return reply;
            }
            if (IQ.Type.get.equals(packet.getType())) {
                throw new RuntimeException("no interface to get it");
            } else if (IQ.Type.set.equals(packet.getType())) {
                Element iq = packet.getElement();
                Element query = iq.element("query");
                Element jid = query.element("jid");
                Element roomJid = query.element("roomJid");
                Element affiliation = query.element("affiliation");
                if (roomJid == null || jid == null || affiliation == null) {
                    reply.setError(PacketError.Condition.item_not_found);
                    return reply;
                }
                // userJid
                JID userJid = XMPPServer.getInstance().createJID(jid.getText(), null);
                WebManager webManager = new WebManager();
                MUCRoom room = webManager.getMultiUserChatManager().getMultiUserChatService("conference").getChatRoom(roomJid.getText());
                IQ mucIq = new IQ(IQ.Type.set);
                // 对内部发起IQ请求
                if ("owner".equals(affiliation.getText()) || "admin".equals(affiliation.getText())) {
                    Element frag = mucIq.setChildElement("query", "http://jabber.org/protocol/muc#owner");
                    Element item = frag.addElement("item");
                    item.addAttribute("affiliation", affiliation.getText());
                    item.addAttribute("jid", userJid.toBareJID());
                    item.addAttribute("nick", userJid.toBareJID());
                    // Send the IQ packet that will modify the room's
                    room.getIQOwnerHandler().handleIQ(mucIq, room.getRole());
                } else if ("member".equals(affiliation.getText()) || "outcast".equals(affiliation.getText())) {
                    Element frag = mucIq.setChildElement("query", "http://jabber.org/protocol/muc#admin");
                    Element item = frag.addElement("item");
                    item.addAttribute("affiliation", affiliation.getText());
                    item.addAttribute("jid", userJid.toBareJID());
                    item.addAttribute("nick", userJid.toBareJID());
                    // Send the IQ packet that will modify the room's
                    room.getIQAdminHandler().handleIQ(mucIq, room.getRole());
                    // 修改昵称?
                    MUCDao.updateNick(room.getID(), userJid.toBareJID(), userJid.toBareJID());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            reply.setError(PacketError.Condition.internal_server_error);
        }
        return reply;
    }

    @Override
    public IQHandlerInfo getInfo() {
        return info;
    }
}
